package com.froggyware.tadpole.core;

import com.froggyware.tadpole.TadObject;
import com.froggyware.tadpole.Tadpole;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: mst
 * Date: Sep 18, 2011
 * Time: 9:59:49 AM
 * To change this template use File | Settings | File Templates.
 */
public class ResultImpl<T> extends ArrayList<T> implements Result<T> {

    @Override
    public long update(String fieldSelector, Object value) {
        long updated = 0;
        Tadpole pole = Tadpole.getInstance();
        for (int i = 0; i < size(); i++) {
            TadObject o = (TadObject) get(i);
            // set the value
            try {
                JXPathContext context = JXPathContext.newContext(o);
                Object oldValue = context.getValue(fieldSelector);
                context.setValue(fieldSelector, value);
                if (oldValue != null) {
                    updated ++;
                }
                pole.save(o);
            } catch (JXPathNotFoundException junfe) {
                // ignore, elemnt does not match. bad design....
            }
        }
        return updated;
    }

    @Override
    public long delete() {
        long deleted = 0;
        Tadpole pole = Tadpole.getInstance();
        for (int i = 0; i < size(); i++) {
            TadObject o = (TadObject) get(i);
            if (pole.delete(o)) {
                deleted ++;
            }
        }
        return deleted;
    }
}
